﻿using Microsoft.AspNetCore.Http;
using System.Text;
using Microsoft.Extensions.Options;
using SJ.Platform.Extend.IOC.Operation;

namespace SJ.Platform.Middleware.Middleware
{
    public class OperationLogMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IOperationLogger _actionLogger;

        public OperationLogMiddleware(RequestDelegate next, IOperationLogger actionLogger)
        {
            _next = next;
            _actionLogger = actionLogger;
        }

        public async Task InvokeAsync(HttpContext httpContext)
        {
            try
            {
                httpContext.Request.EnableBuffering(); // 启用请求体缓冲
                // ... 获取请求相关信息 ...
                string actionName = httpContext.Request.Host+httpContext.Request.Path;
                string userId = httpContext.User.FindFirst("UserId")?.Value;//当前登陆用户
                string details = "";
                if (httpContext.Request.Method.ToLower() == "post")
                {
                    using (StreamReader reader = new StreamReader(httpContext.Request.Body, Encoding.UTF8, true, 1024, true))
                    {
                        details = await reader.ReadToEndAsync();
                        httpContext.Request.Body.Position = 0; // 重置流位置
                    }
                }
                else if (httpContext.Request.Method.ToLower() == "get")
                {
                    details = httpContext.Request.QueryString.ToString();
                }
                DateTime dateTime = DateTime.Now;
                string ip = httpContext.Connection.RemoteIpAddress?.ToString(); // 客户端IP

                // 在请求处理之前记录操作
                await _actionLogger.AddOperationLogger(httpContext.Request.Headers["Authorization"].ToString()?.Replace("Bearer ", ""), actionName, userId, ip, details);
            }
            catch(Exception ex)
            {

            }
            // 调用下一个中间件或终端中间件，这里要放到最后执行，否则不会跳转到下一个中间件
            await _next(httpContext);
        }
    }
}
